﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Drawing;
using System.Threading;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS物流计划地址解析
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WXPlanInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public WXPlanInfoController(ILogger<WXPlanInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            _logger = loggerFactory.CreateLogger<TMSWLPlanAdressAnalysisController>();

        }

        /// <summary>
        /// TMS物流计划地址解析
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostGetWxPlan([FromBody] WXPlanInfoRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMSWLPlanAdressAnalysisResponseDto re = new TMSWLPlanAdressAnalysisResponseDto();
            List<TMSWLPlanAdressAnalysisResponseData> details = new List<TMSWLPlanAdressAnalysisResponseData>();
            string plan_nos = strparm.plan_nos;


            if (plan_nos == "")
            {
                
                strMsg = "plan_nos is null  ";
            }

            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            Dictionary<string, string> plandic = new Dictionary<string, string>(); //计划表插入dic
            try
            {
                if (strMsg == "")
                {
                    string[] planNosArray = null;
                    if (plan_nos.Contains(","))
                    {
                        // 将JSON数组字符串转换为C#数组  
                        planNosArray = JArray.Parse(plan_nos).ToObject<string[]>();
                    }
                    else
                    {
                        // 单个值，通过拆解字符串方式解析 
                        planNosArray = plan_nos.Split(',');
                    }
                   
                    foreach (var item in planNosArray)
                    {
                        
                        dic = new Dictionary<string, string>();
                        dic.Add("ccode", item.ToString());//查询对应物流计划
                        DataTable dz_dt = MethodHelp.GetTableInfo("TMS0066", dic, con);//获取物流计划信息
                        if (dz_dt.Rows.Count > 0)
                        {
                            Dictionary<string, string> urldic = new Dictionary<string, string>(); //查询公用dic
                            urldic.Add("function_description", "TMS地址省市解析");//查看URL配置表地址描述
                            DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                            if (url_dt.Rows.Count > 0)
                            {
                                string s_address_value = "";
                                string salesorder_lineno = "";
                                string begin_jw = "";//发货经纬度
                                string end_jw = "";//收货经纬度
                                string shipping_address = "";//发货地址
                                string delivery_address = "";//收货地址
                                string dr_distance = "";//驾驶距离


                                //销售订单行号特殊处理
                                if (dz_dt.Rows[0]["salesorder_lineno"].ToString()=="")
                                {
                                    salesorder_lineno = dz_dt.Rows[0]["salesorderline"].ToString();
                                }
                                else
                                {
                                    salesorder_lineno = dz_dt.Rows[0]["salesorder_lineno"].ToString();
                                }

                                //发货地址，为高景，进行字符串转换
                                if (dz_dt.Rows[0]["s_address_value"].ToString().Contains("广州高景"))
                                {
                                    shipping_address = "广州高景";
                                }
                                else if(dz_dt.Rows[0]["s_address_value"].ToString().Contains("金湾高景"))
                                {
                                    shipping_address = "金湾高景";
                                }
                                else if (dz_dt.Rows[0]["s_address_value"].ToString().Contains("宜宾高景"))
                                {
                                    shipping_address = "四川高景";
                                }
                                else if (dz_dt.Rows[0]["s_address_value"].ToString().Contains("青海高景"))
                                {
                                    shipping_address = "青海高景";
                                }
                                else if (dz_dt.Rows[0]["s_address_value"].ToString().Contains("四川高臻"))
                                {
                                    shipping_address = "四川高臻";
                                }
                                else
                                {
                                    shipping_address = dz_dt.Rows[0]["s_address_value"].ToString();
                                }


                                //收货地址，为高景，进行字符串转换
                                if (dz_dt.Rows[0]["t_address_value"].ToString().Contains("广州高景"))
                                {
                                    delivery_address = "广州高景";
                                }
                                else if (dz_dt.Rows[0]["t_address_value"].ToString().Contains("金湾高景"))
                                {
                                    delivery_address = "金湾高景";
                                }
                                else if (dz_dt.Rows[0]["t_address_value"].ToString().Contains("宜宾高景"))
                                {
                                    delivery_address = "四川高景";
                                }
                                else if (dz_dt.Rows[0]["t_address_value"].ToString().Contains("青海高景"))
                                {
                                    delivery_address = "青海高景";
                                }
                                else if (dz_dt.Rows[0]["t_address_value"].ToString().Contains("四川高臻"))
                                {
                                    delivery_address = "四川高臻";
                                }
                                else
                                {
                                    delivery_address = dz_dt.Rows[0]["t_address_value"].ToString();
                                }

                                //发货地址，获取基地实际地址
                                if (shipping_address.Contains("高景")|| shipping_address.Contains("高臻"))
                                {
                                    dic = new Dictionary<string, string>();
                                    dic.Add("factory_name", shipping_address);//查询基地地址
                                    DataTable fhdz_dt = MethodHelp.GetTableInfo("TMS0067", dic, con);//获取物流计划信息
                                    if (fhdz_dt.Rows.Count > 0)
                                    {
                                        shipping_address = fhdz_dt.Rows[0]["factory_address"].ToString();
                                    }
                                }

                                //收货地址，获取基地实际地址
                                if (delivery_address.Contains("高景") || shipping_address.Contains("高臻"))
                                {
                                    dic = new Dictionary<string, string>();
                                    dic.Add("factory_name", delivery_address);//查询基地地址
                                    DataTable fhdz_dt = MethodHelp.GetTableInfo("TMS0067", dic, con);//获取物流计划信息
                                    if (fhdz_dt.Rows.Count > 0)
                                    {
                                        delivery_address = fhdz_dt.Rows[0]["factory_address"].ToString();
                                    }
                                }

                                //发货地址省市获取及经纬度
                                string jsonText_begin = "address=" + shipping_address + "&output=json&key=c4dd44ef5830b1db4a2a6ee3c36f2837";
                                Thread.Sleep(1000);
                                var reAgv_begin = DB.httpGet2(url_dt.Rows[0]["interface_url"].ToString() + jsonText_begin, "", "否");
                                var reAgv_begin2 = reAgv_begin.Replace("[]", "null");
                                TMSWLPlanAdressGeoResponseDto psp_begin = JsonConvert.DeserializeObject<TMSWLPlanAdressGeoResponseDto>(reAgv_begin2);
                                if (psp_begin.status != "1")
                                {
                                    strMsg = strMsg + item.ToString() + "-发货地址异常:" + psp_begin.info;
                                }
                                else
                                {
                                    s_address_value = psp_begin.geocodes[0].province + psp_begin.geocodes[0].city;
                                    begin_jw =  psp_begin.geocodes[0].location;
                                }


                                //收货地址省市获取及经纬度
                                string jsonText = "address=" + delivery_address + "&output=json&key=c4dd44ef5830b1db4a2a6ee3c36f2837";
                                Thread.Sleep(1000);
                                var reAgv = DB.httpGet2(url_dt.Rows[0]["interface_url"].ToString() + jsonText, "", "否");
                                var reAgv2 = reAgv.Replace("[]", "null");
                                TMSWLPlanAdressGeoResponseDto psp = JsonConvert.DeserializeObject<TMSWLPlanAdressGeoResponseDto>(reAgv2);
                                if (psp.status!="1")
                                {
                                    strMsg = strMsg + item.ToString() + "-收地址异常" + psp.info;
                                }
                                else
                                {
                                    end_jw= psp.geocodes[0].location;


                                    urldic = new Dictionary<string, string>(); //查询公用dic
                                    urldic.Add("function_description", "TMS两地驾驶距离获取");//查看URL配置表地址描述
                                    DataTable drive_url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                    if (drive_url_dt.Rows.Count>0)
                                    {
                                        string jsonText_jl = "origin=" + begin_jw + "&destination="+ end_jw;
                                        var reAgv_jl = DB.httpGet2(drive_url_dt.Rows[0]["interface_url"].ToString() + jsonText_jl, "", "否");
                                        TMSGeoDrivingResponseDto dr_re = JsonConvert.DeserializeObject<TMSGeoDrivingResponseDto>(reAgv_jl);
                                        if (dr_re.status!="1")
                                        {
                                            strMsg = strMsg + item.ToString() + "-高德驾驶距离获取失败：" + dr_re.info;
                                        }
                                        else
                                        {
                                            dr_distance = dr_re.route.paths[0].distance.Trim();
                                        }
                                    }

                                    details.Add(new TMSWLPlanAdressAnalysisResponseData
                                    {
                                        plan_no= item.ToString(),
                                        end_address = psp.geocodes[0].province + psp.geocodes[0].city,
                                        begin_address = s_address_value,
                                        customer_name = dz_dt.Rows[0]["customer_name"].ToString(),
                                        qty = DB.ToInt(dz_dt.Rows[0]["materialamount"].ToString()) - DB.ToInt(dz_dt.Rows[0]["yfpmount"].ToString()),
                                        customer_code= dz_dt.Rows[0]["customer_code"].ToString(),
                                        saleorder_no = dz_dt.Rows[0]["salesorderno"].ToString(),
                                        saleorderline_no = salesorder_lineno,
                                        material_code = dz_dt.Rows[0]["materialcode"].ToString(),
                                        material_name = dz_dt.Rows[0]["materialname"].ToString(),
                                        saleorder_qty = DB.ToInt(dz_dt.Rows[0]["materialamount"].ToString()),
                                        customer_contacts = dz_dt.Rows[0]["contacts_user"].ToString(),
                                        contacts_tel = dz_dt.Rows[0]["contacts_phone_num"].ToString(),
                                        shipping_address = dz_dt.Rows[0]["s_address_value"].ToString(),
                                        delivery_address = dz_dt.Rows[0]["t_address_value"].ToString(),
                                        drive_distance=DB.ToDouble(dr_distance)
                                    }) ;
                                }

                            }
                        }
                        else
                        {
                            strMsg = "找不到计划号<" + item.ToString() + ">对应TMS物流信息！";
                        }
                    }

                    if (details.Count>0)
                    {
                        re.data = details;
                    }
                    else
                    {
                        strMsg = plandic+"地址解析异常，请联系管理员！";
                    }
                }               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }
            if (strMsg=="")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
